package com.uzai.console.config;

import org.springframework.context.annotation.Configuration;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 处理跨域问题
 * @author jianghan
 * @since 2017/09/28
 */
@WebFilter(filterName = "CorsFilter")
@Configuration
public class CorsFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse servletResponse = (HttpServletResponse) response;
        String origin = req.getHeader("Origin");
        if(origin == null) {
            origin = req.getHeader("Referer");
        }
        //servletResponse.setHeader("Access-Control-Allow-Origin","*"); //这里不能写*，*代表接受所有域名访问，如写*则下面一行代码无效。谨记
        servletResponse.setHeader("Access-Control-Allow-Origin", origin);
        servletResponse.setHeader("Access-Control-Allow-Methods","POST, GET, PATCH, DELETE, PUT");
        servletResponse.setHeader("Access-Control-Max-Age","3600");
        servletResponse.setHeader("Access-Control-Allow-Credentials","true"); //true代表允许携带cookie
        servletResponse.setHeader("Access-Control-Allow-Headers","Origin, X-Requested-With, Content-Type, Accept, Authorization, appKey, auth"); //这里“Authorization”是我要传到后台的内容key
        servletResponse.setHeader("Access-Control-Expose-Headers","Authorization, appKey, auth");
        chain.doFilter(request,response);
    }
}
